package com.asiainfo.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;

import java.util.function.Consumer;

/**
 * 全局过滤器，在网管层过滤请求
 */
@Slf4j
@Component
public class DIYGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到请求对象RequestServer
        ServerHttpRequest request = exchange.getRequest();
        //打印请求来源和请求URL,请求参数等信息
        log.info("请求来源：{}，请求URL：{}，请求参数：{}", request.getRemoteAddress(), request.getPath(), request.getQueryParams());
        //获取当前时间
        long startTime = System.currentTimeMillis();
        //放行 这里是异步调用，需要用doFinally
        return chain.filter(exchange).doFinally(signalType -> {
            //计算请求耗时
            log.info("请求结束，耗时：{}ms", System.currentTimeMillis() - startTime);
        });
    }

    /**
     * 定义优先级
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
